<template>
  <div class="publish-message">
    <el-form :model="messageForm" status-icon ref="messageForm" label-width="100px" class="demo-ruleForm">
      <el-form-item label="标题" prop="title">
        <el-input v-model="messageForm.title"></el-input>
      </el-form-item>
      <el-form-item label="内容" prop="content">
        <el-input type="textarea" v-model="messageForm.content"></el-input>
      </el-form-item>
      <el-form-item label="是否群发" prop="isGroupSend">
        <el-switch v-model="messageForm.isGroupSend"></el-switch>
      </el-form-item>
      <el-form-item label="发送给谁" prop="receiverId" v-if="!messageForm.isGroupSend">
        <el-input v-model="messageForm.receiverId"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { sendMessage } from '@/http/message.js'
import { ElMessage } from 'element-plus'

export default {
  name: 'PublishMessage',
  data() {
    return {
      messageForm: {
        title: '',
        content: '',
        isGroupSend: false,
        receiverId: ''
      }
    }
  },
  methods: {
    submitForm() {
      const formData = new FormData()
      formData.append('title', this.messageForm.title)
      formData.append('content', this.messageForm.content)
      formData.append('isGroupSend', this.messageForm.isGroupSend)

      if (!this.messageForm.isGroupSend) {
        formData.append('receiverId', this.messageForm.receiverId)
      }
      sendMessage(formData)
        .then(resp => {
          console.log('数据：', resp.data)
          console.log('code：', resp.code)
          if (resp.code === 200) {
            ElMessage({
              type: 'success',
              message: '消息发送成功'
            })
            // 可选跳转或清空表单
            this.resetForm()
          } else {
            ElMessage({
              type: 'error',
              message: '消息发送失败，请检查输入信息'
            })
          }
        })
        .catch(err => {
          console.log('发送异常:', err)
          ElMessage({
            type: 'error',
            message: '网络异常，请稍后再试'
          })
        })
    },
    resetForm() {
      this.$refs['messageForm'].resetFields()
    }
  }
}
</script>

<style scoped>
.publish-message {
  padding: 20px;
}
</style>